//
//  SMSelectView.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 2017/7/15.
//  Copyright © 2017年 EasyToTesco. All rights reserved.
//

#import "SMSelectView.h"
#import "AppDelegate.h"
#define kWindow  ((AppDelegate*)([UIApplication sharedApplication].delegate)).window
#define kWLastSelect @"kWLastSelect_%p"

static const CGFloat conHeight = 270;
static const CGFloat cellHeight = 50;


@interface SMSelectCell : UITableViewCell
@property (nonatomic, strong) UIButton *selectionButton;
@property (nonatomic, strong) UILabel *descriptionLabel;
@end

@implementation SMSelectCell

- (UIButton *)selectionButton {
    if (!_selectionButton) {
        _selectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_selectionButton setImage:[UIImage imageNamed:@"rate_select"] forState:UIControlStateSelected];
        [_selectionButton setImage:[UIImage imageNamed:@"rate_normal"] forState:UIControlStateNormal];
        _selectionButton.userInteractionEnabled = false;
        [self addSubview:_selectionButton];
       
    }
    return _selectionButton;
}

- (UILabel *)descriptionLabel {
    if (!_descriptionLabel) {
        _descriptionLabel = [[UILabel alloc] init];
        [_descriptionLabel setFont:[UIFont systemFontOfSize:14]];
        [_descriptionLabel setTextColor: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1/1.0]];
        
        [self addSubview:_descriptionLabel];
        
    }
    return _descriptionLabel;
}


- (void)layoutSubviews
{
    [super layoutSubviews];
    
    WeakSelf(self);
    [_selectionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakself);
        make.right.equalTo(weakself.mas_right).offset(-17);
    }];
    
    [_descriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakself);
        make.left.equalTo(weakself.mas_left).offset(17);
    }];

}


@end

@interface SMSelectView()
<UITableViewDelegate,
UITableViewDataSource>



@property (nonatomic, strong) NSString    *headerStr;
@property (nonatomic, weak) id _Nullable  delegate;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView      *topView;
@property (nonatomic,strong)  UIView      *conView;
@property (nonatomic, strong) UIButton    *cancelBtn;
@property (nonatomic, strong) UIButton    *confirmBtn;
@property (nonatomic, strong) UIView      *bgView;
@property (nonatomic, strong) UILabel     *headerTitleLabel;

@property (nonatomic, strong) NSMutableArray *selectedArray;//已选择的index数组
@property (nonatomic, strong) NSMutableArray *optionsArray;

@end

@implementation SMSelectView


+ (SMSelectView *)showWithTitle:(NSString *)title options:(NSMutableArray *)optionsArray delegate:(id)delegate completionHandler:(completeClickBlock)handler
{
    SMSelectView  *selectView = [[SMSelectView alloc] initWithFrame:kWindow.bounds];
    [kWindow addSubview:selectView];
    
    selectView.selectedArray = [[[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:kWLastSelect, delegate]] mutableCopy];
    if (!selectView.selectedArray) {
        selectView.selectedArray = [NSMutableArray new];
    }

    
    selectView.headerStr = title;
    selectView.optionsArray = [optionsArray copy];
    selectView.completeClickBlock = handler;
    selectView.delegate = delegate;
    
    [selectView.tableView registerClass:[SMSelectCell class] forCellReuseIdentifier:@"SMSelectCell"];
    [selectView.tableView reloadData];

    [selectView layoutIfNeeded];
    [selectView showView:selectView];
    
    return selectView;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor clearColor];
        UIView *bgView = [[UIView alloc] initWithFrame:frame];
        bgView.backgroundColor = [UIColor blackColor];
        bgView.alpha = 0.f;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBgView:)];
        [bgView addGestureRecognizer:tap];
        [self addSubview:bgView];
        
        [self addSubview:self.conView];
        self.bgView = bgView;
    }
    return self;
}


- (void)showView:(SMSelectView *)view {

    [UIView animateWithDuration:0.3 animations:^{
        view.bgView.alpha = 0.5;
        _conView.y = HEIGHT-conHeight;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)closeView:(SMSelectView *)view {
    [UIView animateWithDuration:0.3 animations:^{
        view.bgView.alpha = 0;
        _conView.y = HEIGHT;
    } completion:^(BOOL finished) {
        [view removeFromSuperview];
    }];
}


- (void)setHeaderStr:(NSString *)headerStr
{
    _headerStr = headerStr;
    self.headerTitleLabel.text = headerStr;
}

#pragma makr action
- (void)tapBgView:(UITapGestureRecognizer *)sender {
    [self closeView:self];
}

- (void)tapCancleBtn
{
    [self closeView:self];
}



#pragma mark - TableViewDelegate & DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.optionsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SMSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMSelectCell"];
    cell.descriptionLabel.text = self.optionsArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.selectionButton.selected = NO;
    if ([self.selectedArray containsObject:@(indexPath.row)]) {
        cell.selectionButton.selected = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SMSelectCell *cell = (SMSelectCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.selectionButton.selected = true;
    [self.selectedArray removeAllObjects];
    [self.selectedArray addObject:@(indexPath.row)];
    self.completeClickBlock(indexPath.row);
    [self closeView:self];

}

#pragma mark lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,51,WIDTH,conHeight-71) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.conView addSubview:_tableView];
        _tableView.rowHeight = cellHeight;
        _tableView.bounces = false;
    }
    return _tableView;
}

- (UILabel *)headerTitleLabel
{
    if (!_headerTitleLabel) {
        _headerTitleLabel = [[UILabel alloc]init];
        _headerTitleLabel.text = self.headerStr;
        _headerTitleLabel.font = FONT(16);
        [self.topView addSubview:_headerTitleLabel];
        
        WeakSelf(self);
        [_headerTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(weakself.topView);
        }];
    }
    return _headerTitleLabel;
}

- (UIButton *)confirmBtn
{
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _confirmBtn.backgroundColor = [UIColor whiteColor];
        [_confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_confirmBtn setTitleColor:[UIColor blackColor]  forState:UIControlStateNormal];
        [_confirmBtn addTarget:self action:@selector(tapConfirmBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:_confirmBtn];
        WeakSelf(self);
        [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakself.topView.mas_right).offset(-8);
            make.centerY.equalTo(weakself.topView);
            make.width.height.mas_equalTo(50);
        }];
        
        _confirmBtn.hidden = true;
    }
    return _confirmBtn;
}



- (UIButton *)cancelBtn
{
    if (!_cancelBtn ) {
        _cancelBtn = [[UIButton alloc] init];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_cancelBtn setTitleColor:DEFAULT_COLOR forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(tapCancleBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:_cancelBtn];
        
        WeakSelf(self);
        [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakself.topView.mas_left).offset(8);
            make.centerY.equalTo(weakself.topView);
            make.width.height.mas_equalTo(50);
        }];

    }
    return _cancelBtn;
}


- (UIView *)topView
{
    if (!_topView) {
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_topView];
        _topView.frame = CGRectMake(0,0,WIDTH,50);
        [_topView addSubview:self.cancelBtn];
        [_topView addSubview:self.confirmBtn];
        
    }
    return _topView;
}

- (UIView *)conView
{
    if (!_conView) {
        _conView = [[UIView alloc] init];
        _conView.frame = CGRectMake(0,HEIGHT,WIDTH,conHeight);
        _conView.backgroundColor = BACKGROUND_COLOR;
        [self addSubview:_conView];
        [_conView addSubview:self.topView];
        [_conView addSubview:self.tableView];

    }
    return _conView;
}

@end
